package com.chinapost.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.beans.factory.annotation.Autowired;

import com.chinapost.excelUtil.ExcelUtils;
import com.chinapost.excelUtil.JsGridReportBase;
import com.chinapost.excelUtil.TableColumn;
import com.chinapost.excelUtil.TableData;
import com.chinapost.excelUtil.TableHeaderMetaData;
import com.chinapost.service.DeptServiceI;
import com.chinapost.service.UserServiceI;
import com.chinapost.service.YxsjServiceI;
import com.chinapost.vo.DataGrid;
import com.chinapost.vo.Json;
import com.chinapost.vo.SessionInfo;
import com.chinapost.vo.Yxsj;
import com.chinapost.vo.YxsjTj;
import com.opensymphony.xwork2.ModelDriven;

@Action(value = "yxsjAction", results = { 
		@Result(name = "yxsjManager", location = "/jsp/yxsj/yxsjManager.jsp"),
		@Result(name = "manager", location = "/jsp/yxsj/manager.jsp"),
		@Result(name = "yxsjAdd", location = "/jsp/yxsj/yxsjAdd.jsp"),
		@Result(name = "yxsjImport", location = "/jsp/yxsj/yxsjImport.jsp"),
		@Result(name = "yxsjTjgr", location = "/jsp/tj/yxsjTjgr.jsp"),
		@Result(name = "yxsjTjone", location = "/jsp/tj/yxsjTjone.jsp"),
		@Result(name = "yxsjTjdw", location = "/jsp/tj/yxsjTjdw.jsp"),
		@Result(name = "yxsjTjfy", location = "/jsp/tj/yxsjTjfy.jsp"),
		@Result(name = "yxsjTjfyone", location = "/jsp/tj/yxsjTjfyone.jsp"),
		@Result(name = "yxsjEdit", location = "/jsp/yxsj/yxsjEdit.jsp") })
public class YxsjAction extends BaseAction implements ModelDriven<Yxsj>, ServletRequestAware,ServletResponseAware {

	private Yxsj yxsj = new Yxsj();
	private HttpServletRequest request;
	private HttpServletResponse response;
	@Autowired
	private YxsjServiceI yxsjService;
	@Autowired
	private DeptServiceI deptService;
	@Autowired
	private UserServiceI userService;

	@Override
	public Yxsj getModel() {
		return yxsj;
	}

	public String yxsjManager() {
		SessionInfo si=(SessionInfo)ServletActionContext.getRequest().getSession().getAttribute("sessionInfo");
		String roleIds = si.getRoleIds();
		if (roleIds.contains("9999")){//普通用户的角色ID是9999
			return "manager";//普通用户返回manager.jsp页面
		}else{
			return "yxsjManager";
		}
	}

	public String yxsjAdd() {
		return "yxsjAdd";
	}

	public String yxsjEdit() {
		return "yxsjEdit";
	}

	/**
	 * 个人营销数据统计页面
	 * @return
	 */
	public String yxsjTjgr() {
		SessionInfo si=(SessionInfo)ServletActionContext.getRequest().getSession().getAttribute("sessionInfo");
		String roleIds = si.getRoleIds();
		if (roleIds.contains("9999")){//普通用户的角色ID是9999
			return "yxsjTjone";//普通用户返回页面
		}else{
			return "yxsjTjgr";
		}
	}
	
	/**
	 * 单位营销数据统计页面
	 * @return
	 */
	public String yxsjTjdw() {
		return "yxsjTjdw";
	}
	
	/**
	 * 单位营销数据统计页面
	 * @return
	 */
	public String yxsjTjfy() {
		SessionInfo si=(SessionInfo)ServletActionContext.getRequest().getSession().getAttribute("sessionInfo");
		String roleIds = si.getRoleIds();
		if (roleIds.contains("9999")){//普通用户的角色ID是9999
			return "yxsjTjfyone";//普通用户返回页面
		}else{
			return "yxsjTjfy";
		}
	}
	
	/**
	 * 营销数据导入页面
	 * @return
	 */
	public String yxsjImport() {
		return "yxsjImport";
	}

	public void add() {
		Json j = new Json();
		try {
			String msg = yxsjService.add(yxsj);
			j.setSuccess(true);
			j.setMsg(msg);
		} catch (Exception e) {
			j.setMsg("添加失败！");
		}
		super.writeJson(j);
	}

	public void datagrid() {
		if (!StringUtils.isEmpty(yxsj.getDeptid())) {
			yxsj.setDeptIds(deptService.getChildIds(yxsj.getDeptid()));
		} else {
			SessionInfo s = (SessionInfo) request.getSession().getAttribute("sessionInfo");
			yxsj.setDeptIds(deptService.getChildIds(s.getDeptid()));
		}

		super.writeJsonDate(yxsjService.datagrid(yxsj));
	}
	
	/**
	 * 个人营销数据统计表格
	 */
	public void tjgr_datagrid(){
		DataGrid dg = new DataGrid();
		
		if (!StringUtils.isEmpty(yxsj.getDeptid())) {
			yxsj.setDeptIds(deptService.getAllChildids(yxsj.getDeptid()));
		} else {
			SessionInfo s = (SessionInfo) request.getSession().getAttribute("sessionInfo");
			yxsj.setDeptIds(deptService.getAllChildids(s.getDeptid()));
		}
		if (yxsj.getStartMonth()!=null && yxsj.getEndMonth()!=null){
			dg = yxsjService.datagrid_tjgr(yxsj);
		}

		super.writeJsonDate(dg);
	}
	
	/**
	 * 部门营销数据统计表格
	 */
	public void tjbm_datagrid(){
		List<YxsjTj> lists = new ArrayList<YxsjTj>();
		
		if (!StringUtils.isEmpty(yxsj.getDeptid())) {
			yxsj.setDeptIds(deptService.getAllChildids(yxsj.getDeptid()));
		} else {
			SessionInfo s = (SessionInfo) request.getSession().getAttribute("sessionInfo");
			yxsj.setDeptIds(deptService.getAllChildids(s.getDeptid()));
		}
		if (yxsj.getStartMonth()!=null && yxsj.getEndMonth()!=null){
			lists = yxsjService.excelData_tjbm(yxsj);
		}

		super.writeJsonDate(lists);
	}


	/**
	 * 个人营销费用统计表格
	 */
	public void tjfy_datagrid(){
		DataGrid dg = new DataGrid();
		if (!StringUtils.isEmpty(yxsj.getDeptid())) {
			yxsj.setDeptIds(deptService.getAllChildids(yxsj.getDeptid()));
		} else {
			SessionInfo s = (SessionInfo) request.getSession().getAttribute("sessionInfo");
			yxsj.setDeptIds(deptService.getAllChildids(s.getDeptid()));
		}
		if (yxsj.getStartMonth()!=null && yxsj.getEndMonth()!=null){
			dg = yxsjService.datagrid_tjfy(yxsj);
		}

		super.writeJsonDate(dg);
	}

	
	public void delete() {
		Json j = new Json();
		try {
			yxsjService.delete(yxsj);
			j.setSuccess(true);
			j.setMsg("删除成功！");
			j.setObj(yxsj.getCid());
		} catch (Exception e) {
			j.setMsg("删除失败！");
		}
		super.writeJson(j);
	}

	public void edit() {
		Json j = new Json();
		try {
			yxsjService.edit(yxsj);
			j.setSuccess(true);
			j.setMsg("修改成功!");
		} catch (Exception e) {
			j.setMsg("修改失败！");
		}
		writeJson(j);
	}

	public void addYxsjs() {
		Json j = new Json();
		int count = 0;
		//设置上传的营销数据文件路径在WEB-INF/uploader目录下
		String filepath = ServletActionContext.getServletContext().getRealPath("/") + "WEB-INF\\upload\\";
		yxsj.setFilepath(filepath);
		try {
			count = yxsjService.addYxsjs(yxsj);
			if (count > 0) {
				j.setSuccess(true);
				j.setMsg("导入成功，新增" + count + "条营销数据！");
			} else {
				j.setMsg("导入0条数据！");
			}
		} catch (Exception e) {
			j.setMsg("导入失败,新增0条记录！");
		}
		super.writeJson(j);
	}
	

	@Override
	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}
	
	@Override
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}

	
	public void exportExcel() throws Exception {
		response.setContentType("application/msexcel;charset=GBK");
		SessionInfo s = (SessionInfo) request.getSession().getAttribute("sessionInfo");
		if (!StringUtils.isEmpty(yxsj.getDeptid())) {
			yxsj.setDeptIds(deptService.getChildIds(yxsj.getDeptid()));
		} else {
			yxsj.setDeptIds(deptService.getChildIds(s.getDeptid()));
		}
		List<Yxsj> list = yxsjService.excelData(yxsj);
		String title = "";
		if (!StringUtils.isEmpty(yxsj.getCbh())){
			title = userService.getNameByBh(yxsj.getCbh());
		}else{
			if (!StringUtils.isEmpty(yxsj.getDeptid())){
				title = deptService.getNameById(yxsj.getDeptid());
			}else{
				title = s.getDeptName();
			}
		}
		title += "营销数据表("+yxsj.getStartMonth()+"-"+yxsj.getEndMonth()+")";
		String[] hearders = new String[] { "部门", "编号","姓名", "月份", "开户机构","账号", "卡号（一本通）","业务种类","起息日",  "存期", "金额", "折算积分" };// 表头数组
		String[] fields = new String[] { "deptname", "cbh", "username", "csbyf","ckhj", "czh",  "ckh", "kindname","cqxr", "ccq", "cye", "cjf" };// 对象属性数组
		int[] columnwidths = new int[] { 18, 10, 10, 12, 12, 16, 18, 12, 12, 10, 16, 12 };
		TableData td = ExcelUtils.createTableData(list, getTableHeader(hearders), fields);
		td.compute();
		JsGridReportBase report = new JsGridReportBase(request, response);
		report.exportToExcel(title, "admin", columnwidths, td);
	}
	
	public void exportExcel_tjgr() throws Exception {
		response.setContentType("application/msexcel;charset=GBK");
		SessionInfo s = (SessionInfo) request.getSession().getAttribute("sessionInfo");
		if (!StringUtils.isEmpty(yxsj.getDeptid())) {
			yxsj.setDeptIds(deptService.getChildIds(yxsj.getDeptid()));
		} else {
			yxsj.setDeptIds(deptService.getChildIds(s.getDeptid()));
		}
		List<YxsjTj> list = new ArrayList<YxsjTj>();
		if (yxsj.getStartMonth()!=null && yxsj.getEndMonth()!=null){
			list = yxsjService.excelData_tjgr(yxsj);
		}
		String title = "";
		if (!StringUtils.isEmpty(yxsj.getCbh())){
			title = userService.getNameByBh(yxsj.getCbh());
		}else{
			if (!StringUtils.isEmpty(yxsj.getDeptid())){
				title = deptService.getNameById(yxsj.getDeptid());
			}else{
				title = s.getDeptName();
			}
		}
		title += "个人营销数据统计表("+yxsj.getStartMonth()+"-"+yxsj.getEndMonth()+")";
		String[] hearders = new String[] { "部门", "编号","姓名", "营销总积分", "本年计划", "完成比例(%)" };// 表头数组
		String[] fields = new String[] { "deptname", "cbh", "username", "czjf", "cjh",  "cbl" };// 对象属性数组
		int[] columnwidths = new int[] { 18, 10, 10, 16, 18, 18 };
		TableData td = ExcelUtils.createTableData(list, getTableHeader_tjgr(hearders), fields);
		td.compute();
		JsGridReportBase report = new JsGridReportBase(request, response);
		report.exportToExcel(title, "admin", columnwidths, td);
	}
	
	public void exportExcel_tjbm() throws Exception {
		response.setContentType("application/msexcel;charset=GBK");
		SessionInfo s = (SessionInfo) request.getSession().getAttribute("sessionInfo");
		if (!StringUtils.isEmpty(yxsj.getDeptid())) {
			yxsj.setDeptIds(deptService.getAllChildids(yxsj.getDeptid()));
		} else {
			yxsj.setDeptIds(deptService.getAllChildids(s.getDeptid()));
		}
		List<YxsjTj> list = new ArrayList<YxsjTj>();
		if (yxsj.getStartMonth()!=null && yxsj.getEndMonth()!=null){
			list = yxsjService.excelData_tjbm(yxsj);
		}
		String title = "";
		if (!StringUtils.isEmpty(yxsj.getDeptid())){
			title = deptService.getNameById(yxsj.getDeptid());
		}else{
			title = s.getDeptName();
		}
		title += "部门营销数据统计表("+yxsj.getStartMonth()+"-"+yxsj.getEndMonth()+")";
		String[] hearders = new String[] { "部门", "营销总积分", "本年总计划", "完成比例(%)" };// 表头数组
		String[] fields = new String[] { "deptname", "czjf", "cjh",  "cbl" };// 对象属性数组
		int[] columnwidths = new int[] { 24, 24, 24, 20};
		TableData td = ExcelUtils.createTableData(list, ExcelUtils.createTableHeader(hearders), fields);
		JsGridReportBase report = new JsGridReportBase(request, response);
		report.exportToExcel(title, "admin", columnwidths, td);
	}
	
	public void exportExcel_tjfy() throws Exception {
		response.setContentType("application/msexcel;charset=GBK");
		SessionInfo s = (SessionInfo) request.getSession().getAttribute("sessionInfo");
		if (!StringUtils.isEmpty(yxsj.getDeptid())) {
			yxsj.setDeptIds(deptService.getAllChildids(yxsj.getDeptid()));
		} else {
			yxsj.setDeptIds(deptService.getAllChildids(s.getDeptid()));
		}
		List<YxsjTj> list = new ArrayList<YxsjTj>();
		if (yxsj.getStartMonth()!=null && yxsj.getEndMonth()!=null){
			list = yxsjService.excelData_tjfy(yxsj);
		}
		String title = "";
		if (!StringUtils.isEmpty(yxsj.getCbh())){
			title = userService.getNameByBh(yxsj.getCbh());
		}else{
			if (!StringUtils.isEmpty(yxsj.getDeptid())){
				title = deptService.getNameById(yxsj.getDeptid());
			}else{
				title = s.getDeptName();
			}
		}
		title += "营销奖励统计表("+yxsj.getStartMonth()+"-"+yxsj.getEndMonth()+")";
		String[] hearders = new String[] { "部门", "编号","姓名", "营销总积分", "营销奖励" };// 表头数组
		String[] fields = new String[] { "deptname","cbh","username", "czjf", "cjh"};// 对象属性数组
		int[] columnwidths = new int[] { 20, 18, 18,22,20};
		TableData td = ExcelUtils.createTableData(list, ExcelUtils.createTableHeader(hearders), fields);
		JsGridReportBase report = new JsGridReportBase(request, response);
		report.exportToExcel(title, "admin", columnwidths, td);
	}
	
	/**
	 * 营销数据表头
	 * @param hearders
	 * @return
	 */
	private TableHeaderMetaData getTableHeader(String[] hearders) {
		int spanCount = 2;//需要合并的列数，从第1列到第几列合并
		// 创建表头对象
		TableHeaderMetaData headMeta = new TableHeaderMetaData();
		for (int i = 0; i < hearders.length; i++) {
			TableColumn tc = new TableColumn();
			tc.setDisplay(hearders[i]);

			// 设置按指定列统计
			if (i == 1)// 按第1列进行小计
				tc.setDisplaySummary(true);

			if (i > 8)// 对指定列进行求和,从0开始计算列
				tc.setAggregateRule("sum");

			if (i < spanCount)// 合并
				tc.setGrouped(true);
			headMeta.addColumn(tc);
		}
		return headMeta;
	}

	/**
	 * 统计个人营销数据
	 * @param hearders
	 * @return
	 */
	private TableHeaderMetaData getTableHeader_tjgr(String[] hearders) {
		int spanCount = 1;//需要合并的列数，从第1列到第几列合并
		// 创建表头对象
		TableHeaderMetaData headMeta = new TableHeaderMetaData();
		for (int i = 0; i < hearders.length; i++) {
			TableColumn tc = new TableColumn();
			tc.setDisplay(hearders[i]);

			// 设置按指定列统计
			if (i == 0)// 按第1列进行小计
				tc.setDisplaySummary(true);

			if (i ==3 || i ==4)// 对指定列进行求和,从0开始计算列
				tc.setAggregateRule("sum");
			if (i ==5){//对指定列求平均数
				tc.setAggregateRule("avg");
			}

			if (i < spanCount)// 合并
				tc.setGrouped(true);
			headMeta.addColumn(tc);
		}
		return headMeta;
	}

}
